<?php
/**
 * Introduction: 全返表  quanfan
 */

namespace Common\Model;


use Think\Model;

class QuanfanModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'quanfan';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }

    /**
     * 99活动，取消一小时内购买
     * @return array
     */
    public function addOrder($orderInfo){
        $data['member_id'] = $memberId = $orderInfo['memberId'];
        $data['shop_id'] = $orderInfo['shopId'];
        $data['order_id'] = $orderInfo['orderId'];
        $data['order_type'] = $orderInfo['orderType'];
        $data['order_price'] = $order_price = $orderInfo['price'];
        $data['pay_time'] = time();
        $model = new ActivityCommonModel();
        $activeInfo = $model->where("id=".$data['order_type'])->find();
        file_put_contents('/www/web_api/abc.txt',json_encode($activeInfo));

        if(empty($activeInfo)){
            return false;
        }

        $rule = explode('-', $activeInfo['rule']);
        $price_min = $rule[2];
        $order_hist = $this->where("member_id=$memberId and order_type=".$data['order_type'])->select();

        // TODO:test
        $hist = empty($order_hist) ? 1: 2;
        $model = new OrderLogModel();
        $model->add(['order_id'=>$data['order_id'],'admin_name'=>'顾客','text'=>"orderType: ".$data['order_type'].", min:$rule[2],orderPrice:".$orderInfo['order_price'].",hist:$hist",'behavior'=>"test quanfan"]);
        file_put_contents('/www/web_api/aa.txt',$hist);
        if(empty($order_hist) && $data['order_price'] >= $price_min){
            // 只返50%, 最高返500
            $data1['return_price'] = $data['order_price'] * 0.5;
            $data1['return_price'] = ($data['return_price'] > 1000) ? 1000 : $data['return_price'];
            $data1['order_key'] = 1;
            $order_id = $this->add($data1);
            file_put_contents('/www/web_api/aaa.txt',$order_id);
            if(!$order_id){
                return false;
            }

            // 第一单返代金券：满足最低消费，返订单总额的50%
            $this->handOutCoupons($memberId, $data['return_price']);

            // 添加、修改全返统计信息
            $model = new QuanfanCountModel();
            $ret_update = $model->updateByUserId($memberId, $data1);

            if(!$ret_update){
                return false;
            }
        }

        return true;
    }

    /**
     * 分发优惠券
     * @param $memberId
     * @param $price
     * @return bool
     */
    public function handOutCoupons($memberId, $price){
        $couponsList = $this->createCouponsAmount($price);

//        $memberId    = $this->getMemberId(true);
        $date = date("Y-m-d");

        $couponsObj = new MicroShopCouponsModel();

        foreach ($couponsList as $item_coupons) {
            $couponsInfo = array(
                'title'     => "首单全额福利，福利50%代金券",
                'cpns_if'   => 0,
                'cpns_then' => $item_coupons,
                'start_time'    => date("Y-m-d",strtotime("+1 days")) . " 00:00:00",
                'end_time'      => date("Y-m-d",strtotime("+60 days")) . " 23:59:59"
            );

            $couponsCode = $this->createCouponsCode();

            $couponsObj->addCoupons($memberId, 0, $couponsCode, $couponsInfo);
        }

        return true;
    }

    /**
     * 创建优惠码
     * 不会重复
     * @param int $length
     * @param string $codePre
     * @return string
     */
    public function createCouponsCode($length = 10, $codePre = ""){
        $codeArr = array();

        for ($i = 0; $i < ($length- strlen($codePre)); $i ++) {
            $type = mt_rand(1, 2);

            if($i == 0 || $type == 1){//字母，保证第一个是字母
                $ascii = "";

                while (true) {
                    $ascii = mt_rand(65, 90);
                    if ($ascii != 79 && $ascii != 73) {
                        // 排除O字母和I
                        break;
                    }
                }
                $codeArr[] = chr($ascii);
            }else{//数字
                $num = mt_rand(2, 9);
                $codeArr[] = $num;
            }
        }

        $code = implode('', $codeArr);

        strlen($codePre) > 0 && $code = $codePre.$code;

        return $code;
    }

    /**
     * 计算优惠券金额列表
     *
     * @param $total_price
     * @return array
     */
    private function createCouponsAmount($total_price){
        $coupons = array();

        // 根据不同金额，生产不同面值的代金券，并且面额是10的整数倍；
        if($total_price <= 50){
            $count = (int)floor($total_price/10);

            for($i = 0; $i < $count; $i++){
                $coupons[] = 10;
            }
        }elseif($total_price > 50 && $total_price <=100){
            $coupons[] = 25;
            $coupons[] = 25;
            $count = (int)floor(($total_price - 50)/10);

            for($i = 0; $i < $count; $i++){
                $coupons[] = 10;
            }
        }elseif($total_price > 100 && $total_price <=200){
            $coupons[] = 25;
            $coupons[] = 25;
            $coupons[] = 25;
            $coupons[] = 25;

            $count = (int)floor(($total_price - 100)/10);

            for($i = 0; $i < $count; $i++){
                $coupons[] = 10;
            }
        }elseif($total_price > 200 && $total_price <=500){
            $coupons[] = 50;
            $coupons[] = 50;
            $coupons[] = 25;
            $coupons[] = 25;
            $coupons[] = 25;
            $coupons[] = 25;

            $rest = $total_price - 200;

            if($rest < 100){
                $count = (int)floor(($rest)/10);

                for($i = 0; $i < $count; $i++){
                    $coupons[] = 10;
                }
            }else{
                $count = (int)floor(($rest)/50);

                for($i = 0; $i < $count; $i++){
                    $coupons[] = 50;
                }

                // 分50份后，还有大于10的金额，则按照10来分
                $count = (int)floor(($rest - $count * 50)/10);

                if($count > 0){
                    for($i = 0; $i < $count; $i++){
                        $coupons[] = 10;
                    }
                }
            }
        }elseif($total_price > 500 && $total_price <=1000){
            $count = (int)floor(($total_price)/50);

            for($i = 0; $i < $count; $i++){
                $coupons[] = 50;
            }

            // 分50份后，还有大于10的金额，则按照10来分
            $count = (int)floor(($total_price - $count * 50)/10);

            if($count > 0){
                for($i = 0; $i < $count; $i++){
                    $coupons[] = 10;
                }
            }
        }elseif($total_price >1000){
            $count = (int)floor(($total_price)/100);

            for($i = 0; $i < $count; $i++){
                $coupons[] = 100;
            }

            // 分100份后，还有大于10的金额，则按照10来分
            $count = (int)floor(($total_price - $count * 100)/10);

            if($count > 0){
                for($i = 0; $i < $count; $i++){
                    $coupons[] = 10;
                }
            }
        }

        rsort($coupons);

        return $coupons;
    }

}